package com.idea.relax.exception.core.registry;


import com.idea.relax.exception.constant.EkConstant;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @className: ConfigInitializer
 * @author: salad
 * @date: 2023/05/26
 * @description: 配置初始化器
 **/
public class ConfigInitializer implements EnvironmentPostProcessor, Ordered {


	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		MutablePropertySources propertySources = environment.getPropertySources();
		initDocTitle(environment, propertySources);
		initEnumScanPkg(environment, application, propertySources);
	}

	/**
	 * 初始化relax.exception-kit.enum-scan-package属性
	 *
	 * @param environment
	 * @param application
	 * @param propertySources
	 */
	private static void initEnumScanPkg(ConfigurableEnvironment environment, SpringApplication application, MutablePropertySources propertySources) {
		Set<String> prop = environment.getProperty(EkConstant.ENUM_SCAN_PACKAGE_KEY, Set.class);
		if (CollectionUtils.isEmpty(prop)) {
			String appPackage = application.getMainApplicationClass().getPackage().getName();
			Map<String, Object> map = new HashMap<>(2);
			Set<String> set = new HashSet<>();
			set.add(appPackage);
			map.put(EkConstant.ENUM_SCAN_PACKAGE_KEY, set);
			propertySources.addLast(new MapPropertySource("RELAX_EK_APP_PACKAGE_PREFIX", map));
		}
	}

	/**
	 * 初始化文档标题
	 *
	 * @param environment
	 * @param propertySources
	 */
	private static void initDocTitle(ConfigurableEnvironment environment, MutablePropertySources propertySources) {
		String docTitle = environment.getProperty(EkConstant.DOC_TITLE_KEY, "");
		if (docTitle.trim().length() == 0) {
			Map<String, Object> map = new HashMap<>(2);
			map.put(EkConstant.DOC_TITLE_KEY, environment.getProperty("spring.application.name", "").concat(" 异常码"));
			propertySources.addLast(new MapPropertySource("RELAX_EK_SERVER_NAME", map));
		}
	}


	@Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE;
	}

}
